package net.qiqb.module;

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 服务代理对象
 *
 * @param <T>
 */
public class ServiceAgent<T> implements InvocationHandler {

    private Class<T> interfaceClass;

    private ModuleContext moduleContext;

    private Object target;

    public ServiceAgent(Class<T> interfaceClass, ModuleContext moduleContext) {
        this.interfaceClass = interfaceClass;
        this.moduleContext = moduleContext;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (target == null) {
            // 尝试从
            final ModuleServiceConfig serviceConfig = moduleContext.getServiceConfig(interfaceClass.getName());
            if (serviceConfig == null) {
                //
                throw new IllegalStateException("获取不到代理到目标对象");
            }
            this.target = serviceConfig.getTarget();
        }
        if (target != null) {
            return ReflectUtil.invoke(target, method, args);
        }
        throw new IllegalStateException("代理获取不到目标对象");
    }
}
